package com.dengqi.mymodule.activity.fragment.recycleview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

/**
 * @Author: dengqi
 * @CreateDate: 2020/10/19 17:31
 * @Description: 只能用于简单的布局 套recycleview的布局不行
 */
public abstract class QRecycledapter<T> extends RecyclerView.Adapter<QRecycledapter.ViewHolder> {

    private List<T> data = new ArrayList<>();
    protected OnItemClickListener<T> onItemClickListener;//单击事件

    public void setData(List<T> data){
        if(data!=null){
            this.data = data;
        }
    }

    public void addData(List<T> data){
        if(data!=null){
            this.data.addAll(data);
        }
    }

    public void clearData(){
        this.data.clear();
    }

    public abstract int getLayoutResId();
    public abstract void bindData(T object, View itemView, int position);

    @NonNull
    @Override
    public QRecycledapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getLayoutResId(), parent,false);
        QRecycledapter.ViewHolder viewHolder = new QRecycledapter.ViewHolder(view);
        return viewHolder;
    }
    @Override
    public void onBindViewHolder(@NonNull QRecycledapter.ViewHolder holder, int position) {
        T object = data.get(position);
        bindData(object, holder.itemView, position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onItemClickListener!=null){
                    onItemClickListener.onItemClick(object, v, position);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener<T> {
        void onItemClick(T object, View view, int position);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }
}